const BASE_URL = 'http://192.168.8.217:3000'

class GCRequest {
  request<T>(
    url: string,
    method:
      | 'OPTIONS'
      | 'GET'
      | 'HEAD'
      | 'POST'
      | 'PUT'
      | 'DELETE'
      | 'TRACE'
      | 'CONNECT'
      | undefined,
    params?: string
  ): Promise<T> {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('token')
      console.log(token, 'token')
      wx.request({
        url: BASE_URL + url,
        method: method,
        data: params,
        header: {
          Authorization: 'Bearer ' + token
        },
        success: function (res) {
          const data = res.data as any
          if (res.statusCode === 401) {
            wx.showModal({
              title: '提示',
              content: '该功能需要登录，确认登录吗',
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/login/login'
                  })
                } else {
                  wx.switchTab({
                    url: '/pages/home/home'
                  })
                }
              }
            })
            resolve(data)
          }
          if (data.error) {
            wx.showToast({
              icon: 'none',
              title: data.message
            })
            return
          }
          resolve(data)
        },
        fail: function (err) {
          reject(err)
        }
      })
    })
  }
  get<T = any>(url: string, params?: any) {
    return this.request<T>(url, 'GET', params)
  }
  post<T = any>(url: string, params?: any) {
    return this.request<T>(url, 'POST', params)
  }
  delete<T = any>(url: string, params?: any) {
    return this.request<T>(url, 'DELETE', params)
  }
}

const gcRequest = new GCRequest()
export default gcRequest